package com.example.learnsqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBManager {
    private SQLiteDatabase db;
    private DBHelper dbHelper;

    public DBManager(Context context) {
        dbHelper = new DBHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    public void addList(List<Person> persons) {
        db.beginTransaction();
        ContentValues contentValues = new ContentValues();

        try {
            for (Person person : persons) {
                contentValues.put("name", person.getName());
                contentValues.put("age", person.getAge());
                db.insert("person", null, contentValues);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public List<Person> getList() {
        Cursor cursor = queryTheCursor();
        List<Person> persons = new ArrayList<Person>();
        while (cursor.moveToNext()) {
            Person person = new Person();
            person.set_id(cursor.getInt(cursor.getInt(cursor
                    .getColumnIndex("_id"))));
            person.setName(cursor.getString(cursor.getColumnIndex("name")));
            person.setAge(cursor.getInt(cursor.getColumnIndex("age")));

            persons.add(person);
        }
        cursor.close();
        return persons;
    }

    public void updateAge(Person person) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("age", person.getAge());
        db.update("person", contentValues, "name = ?",
                new String[] { person.getName() });
    }

    public void deleteOldPerson(int age) {
        db.delete("person", "age > ?", new String[] { String.valueOf(age) });
    }

    public Cursor queryTheCursor() {  
        Cursor c = db.rawQuery("SELECT * FROM person", null);
        return c;  
    }

    public void closeDB() {
        db.close();
    }
}
